<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ws-queue</title>
</head>
<body>
<div>
    <p id="response"></p>
</div>
</body>
</html>
<!-- 独立JS -->
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/sockjs-client/1.4.0/sockjs.js" charset="utf-8"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.js" charset="utf-8"></script>
<script>
    var stompClient = null;
    //加载完浏览器后  调用connect（），打开双通道
    $(function () {
        //打开双通道
        connect()
    })
    //强制关闭浏览器  调用websocket.close（）,进行正常关闭
    window.onunload = function () {
        disconnect()
    }

    function connect() {
        var userId = "admin";
        var socket = new SockJS('http://127.0.0.1:8089/ws'); //连接SockJS的endpoint名称为"endpointOyzc"
        stompClient = Stomp.over(socket);//使用STMOP子协议的WebSocket客户端
        stompClient.connect({}, function (frame) {//连接WebSocket服务端
            console.log('Connected:' + frame);
            //通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息
            stompClient.subscribe('/user/' + userId + '/queue', function (response) {
                var message = JSON.parse(response.body);
                var response = $("#response");
                response.append("<p>只有userID为" + message.userId + "的人才能收到</p>");
            });
        });
    }

    //关闭双通道
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        console.log("Disconnected");
    }
</script>